package com.fh.shop.api.cate.biz;

import com.alibaba.fastjson.JSON;
import com.fh.shop.api.cate.mapper.ICateMapper;
import com.fh.shop.api.cate.po.Cate;
import com.fh.shop.api.common.ServerResponse;
import com.fh.shop.api.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service("cateService")
@Transactional(rollbackFor = Exception.class)
public class ICateServiceImpl implements ICateService {
    @Autowired
    private ICateMapper cateMapper;


    @Override
    @Transactional(readOnly = true)
    public ServerResponse findList() {
        //每次先从缓存服务器查找
        String cateListJson = RedisUtil.get("cateList");
        if (StringUtils.isNotEmpty(cateListJson)){
            //json格式的字符串 转 java对象 [fastjson]
            List<Cate> cates = JSON.parseArray(cateListJson, Cate.class);
            // 缓存中有数据，直接返回数据
            return ServerResponse.success(cates);
        }
        // 缓存中没有数据，去数据库查找
        List<Cate> cates = cateMapper.selectList(null);
        //java对象转json [fastjson]
        cateListJson = JSON.toJSONString(cates);
        //将查找到的数据，往缓存中存一份
        RedisUtil.set("cateList",cateListJson);
        //响应数据给前台
        return ServerResponse.success(cates);
    }
}
